package com.sushe.service;

import com.sushe.dao.BedAssignmentDao;
import com.sushe.dao.RoomDao;
import com.sushe.dao.StudentDao;
import com.sushe.service.jiekou.BedAssignmentService;

import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

public class BedAssignmentServiceImpl implements BedAssignmentService {

    private StudentDao studentDao=new StudentDao();
    private BedAssignmentDao bedAssignmentDao=new BedAssignmentDao();
    private RoomDao roomDao=new RoomDao();


    @Override
    public  void bedAssignment() throws SQLException, ClassNotFoundException {
        Scanner sc=new Scanner(System.in);
        //选择分配的学生
        System.out.println("请输入要分配的学生姓名：");
        String name=sc.nextLine();
        Integer studentId= studentDao.getStudentId( name);
        if(studentId==null){
            System.out.println("没有此学生！");
            return;
        }
        System.out.println("对应学生ID为："+studentId);

        //判断学生是否已分配宿舍，如果已分配则不能再分配
        Integer watchBedNumber=bedAssignmentDao.getBedNumberByStudentId(studentId);
        if(watchBedNumber!=null){
            System.out.println("该学生已分配宿舍，请勿重复分配！");
            return;
        }


        //输入宿舍楼并判断是否存在
        System.out.println("请输入宿舍楼栋编号Id：");
        Integer  buildingId = sc.nextInt();
        //判断该楼栋编号是否存在，不存在则报错并返回结束方法
        String buildingName= bedAssignmentDao.selectByBuildingId(buildingId);
        System.out.println("楼栋名称为："+buildingName);
        if(buildingName== null){
            System.out.println("该楼栋不存在");
            return;
        }

        //用户输入房间号判断是否存在
        System.out.println("请输入宿舍房间号：");
        String roomNumber=sc.next();
        //判断房间是否存在
        Integer roomId=roomDao.selectByRoomNumberAndBuildingId(roomNumber,buildingId);
        if(roomId==null){
            System.out.println("该房间不存在");
            return;
        }

        //枚举所有可分配的床位集合
        List<Integer> list =null;
        while(true) {
            System.out.println("请选择分配的床位号：");
            list=bedAssignmentDao.getEmptyBedNumbersByRoomId(roomId);
            if(list==null&&list.size()==0){
                System.out.println("该房间没有空床位,请重新选择");
                continue;
            }
            if(list!=null&&list.size()!=0)
                break;
        }
        System.out.println("该房间所有可分配的床位号为：");
        for(Integer bedNumber:list){
            System.out.print(bedNumber+"  ");
        }
        System.out.println();


        System.out.print("请输入您要选择分配的床位号：");
        int bedNumber=sc.nextInt();
        for(Integer bedNumber1:list){
            if(bedNumber==bedNumber1){
                bedAssignmentDao.addBedAssignment(bedNumber,roomId,studentId);
                System.out.println("分配成功！");
                return;
            }
        }
        System.out.println("选择了非法床位！无法分配！");
        return;



    }
}
